package com.bill.learn.web;

import com.bill.learn.entity.Department;
import com.bill.learn.entity.Employee;
import com.bill.learn.entity.EmployeeDTO;
import com.bill.learn.service.DepartmentService;
import com.bill.learn.service.EmployeeService;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author Bill Ludwig; 2020/5/14 19:01
 */
@Controller
@RequestMapping("/emps")
public class EmployeeController {

    @Resource
    Logger logger;

    @Resource
    EmployeeService employeeService;

    @Resource
    DepartmentService departmentService;

    @RequestMapping
    public String list(Model model) {
        List<EmployeeDTO> all = employeeService.getEmployees();
        model.addAttribute("emps", all);
        return "emps/list";
    }

    @GetMapping("/add")
    public String addPage(Model model) {
        List<Department> departments = departmentService.getDepartments();
        model.addAttribute("departments", departments);

        return "emps/add";
    }

    @PostMapping("/add")
    public String addEmp(Employee employee) {
        logger.info("Save方法调用--》      " + employee);
        employeeService.addEmployee(employee);
        return "redirect:/emps";
    }


    @GetMapping("/edit/{id}")
    public String editEmpPage(@PathVariable("id") Integer id, Model model) {

        Employee employee = employeeService.getEmployeeById(id);
        model.addAttribute("emp", employee);

        List<Department> departments = departmentService.getDepartments();
        model.addAttribute("departments", departments);
        return "emps/edit";
    }

    @PostMapping("/edit")
    public String editEmp(Employee employee) {
        employeeService.updateEmployee(employee);
        logger.info("edit方法调用--》       " + employee);
        return "redirect:/emps";
    }

    @GetMapping("/delete/{id}")
    public String deleteEmpPage(@PathVariable("id") Integer id) {
        employeeService.deleteEmployee(id);
        return "redirect:/emps";
    }
}
